package m.store.action;

import m.appserver.AuthInfoUtil;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.model.OrderModel;
import m.store.model.PayAmount;
import m.store.model.PayAmountRecord;
import m.store.service.PayAmountService;
import m.store.service.StoreNumberService;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "store/payAmount")
public class PayAmountAction extends OrderModelAction {
    private PayAmount model;
    private List<PayAmountRecord> stockList;

    /**
     * 保存
     */
    @RequestMeta(transaction = true,logTitle = "付款信息",logDescription = "保存付款信息")
    public JSONMessage doSave() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(PayAmountService.class).save(model,stockList);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    @RequestMeta(transaction = true,logTitle = "付款信息",logDescription = "保存并提交付款信息")
    public JSONMessage doSaveAndSubmit() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        getService(PayAmountService.class).saveAndSubmit(model,stockList);
        return new JSONMessage(0,"提交成功");
    }
    @RequestMeta(transaction = true,logTitle = "付款信息",logDescription = "删除付款信息")
    public JSONMessage doDelete() throws Exception {
        getService(PayAmountService.class).delete(model.getOid(),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"删除成功");
    }
    @RequestMeta(transaction = true,logTitle = "付款信息",logDescription = "审核通过付款信息")
    public JSONMessage doCheck() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Finance);
        getService(PayAmountService.class).check(model.getOid(),model.getPayDate(),model.getRemark(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"审核成功");
    }
    @RequestMeta(transaction = true,logTitle = "付款信息",logDescription = "提交付款信息")
    public JSONMessage doRefund() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Finance);
        getService(PayAmountService.class).refund(model.getOid(),PowerUtil.getSessionStore(true),PowerUtil.getSessionUser(true));
        return new JSONMessage(0,"退回成功");
    }
    /*
     * 编辑付款
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            stockList=ModelQueryList.getModelList(PayAmountRecord.class,new String[]{"*","stock.*"},null,
                    QueryCondition.eq("pay.oid",model.getOid()));
        }else{
            model=new PayAmount();
            model.setOrderNo(StoreNumberService.getNextPayNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setPayDate(new Date());
            stockList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Finance);

        ModelForm form = new ModelForm("入库付款信息");
        form.addItem(
            FormHtml.inputStyle("付款单号","{{model.orderNo}}"),
            FormInput.selectOneModel("收款客户", "model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2).setEdit(edit),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("付款金额","<b>{{stockList.length?formatNumber(model.payAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormInput.date("付款日期","model.payDate").setEdit(edit||check).setRequired(true),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model)
        .addWatch("model.guest.oid","this.stockList=[];")
        .addButton(
            edit? FormButton.pri("保存","doSave"):null,
            edit?FormButton.succ("提交","doSaveAndSubmit").setConfirm("确定要提交吗？"):null,
            check?getCheckFormButton(model.getOid()):null,
            check?FormButton.warn("退回","doRefund").setConfirm("确定要退回吗？"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,stockList:this.stockList}")
                .fillData("model"),
            FormEvent.doJson("doSaveAndSubmit",actionUrl("doSaveAndSubmit"),"{model:this.model,stockList:this.stockList}")
                .success("backFlag"),
            FormEvent.doJson("doCheck",actionUrl("doCheck"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.doJson("doRefund",actionUrl("doRefund"),"{model:this.model}")
                .success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("入库订单").setEdit(edit,true,"{stock:{}}",false);
        form1.setData("stockList",stockList)
        .addMethod(
            FormEvent.custom("editDataAfter",
                "var sum=0.0;" +
                "for(var i=0;i<this.stockList.length;i++){" +
                " sum+=(this.stockList[i].payAmount||0);" +
                "}" +
                "this.model.payAmount=sum;"
            )
        )
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("入库单号","stock.orderNo",130)
                .setEdit(TableEdit.selectOneModel("'action/store/stockInfo/selectOneChecked?params[guest.oid]='+model.guest.oid",900,"stock","orderNo")),
            TableColumn.center("入库日期","stock.stockDate",100).setDateFormat("yyyy-MM-dd")
                .setEdit(Element.tag("div").E("{{formatDate(editRecord.stock.stockDate,'yyyy-MM-dd')}}")),
            TableColumn.number("入库金额","stock.stockAmount",90).isSum(false)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.stock.stockAmount,'#,##0.00')}}")),
            TableColumn.number("尚欠金额","stock.oweAmount",90)
                .setEdit(Element.tag("div").E("{{formatNumber(editRecord.stock.oweAmount,'#,##0.00')}}")),
            TableColumn.number("付款金额","payAmount")
                .setEdit(TableEdit.number()),
            TableColumn.text("备注","remark")
                .setEdit(TableEdit.input())
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    public VueResult toView() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.name","inputUser.realname","checkUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
        }else{
            throw AuthInfoUtil.noPowerException;
        }
        ModelForm form = new ModelForm("入库付款信息");
        form.addItem(
            FormHtml.inputStyle("付款单号", "{{model.orderNo}} {{dict('m.store.model.PayAmount!status',model.status)}}"),
            FormHtml.inputStyle("登记人", "{{model.inputUser.realname}} {{formatDate(model.submitDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("审核人", "{{model.checkUser.realname}} {{formatDate(model.checkDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("付款日期","{{formatDate(model.payDate,'yyyy-MM-dd')}}"),
            FormHtml.inputStyle("收款客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("付款金额", "<b>{{formatNumber(model.payAmount,'#,##0.00')}}</b>"),
            FormHtml.inputStyle("备注","{{model.remark}}").setSpan(3)
        )
        .addData("model",model)
        .addMethod(
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        LoadPage recordPage=new LoadPage("loadRecordPage",actionUrl(PayAmountRecordAction.class,"recordList"),"{params:{'pay.oid':this.model.oid}}")
                .setMounted("this.loadRecordPage();");
        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(recordPage);
    }
    /*
     * 我的付款列表
     */
    public VueResult myInputList() throws Exception {
        VueListResult result=getVueListResult("我的入库付款登记",PayAmount.class,actionUrl("myInputList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("付款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("收款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toDateColumn("付款时间", "payDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.addCol(toSpaceColumn("操作", 140,
            ListElement.test("record.status=='"+ OrderModel.Status_Register+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.status=='"+OrderModel.Status_Register+"'",
                ListButton.ajax("删除", ButtonType.ERROR,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("确定要删除吗？")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.page("登记付款", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
        );
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("付款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款时间","payDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUser(true).getOid()));
        return result;
    }
    /*
     * 待审核列表
     */
    public VueResult checkList() throws Exception {
        VueListResult result=getVueListResult("入库付款待审核",PayAmount.class,actionUrl("checkList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("付款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("收款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toDateColumn("付款时间", "payDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        fillOrderColumn(result);
        if(PowerUtil.hasPower(PowerUtil.Finance)) {
            result.addCol(toSpaceColumn("操作", 100,
                ListButton.page("审核", ButtonType.PRIMARY, actionUrl("toEdit"),  SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid")
            ).setFixed(Align.RIGHT));
        }
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("付款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款时间","payDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("status",OrderModel.Status_Check));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    /*
     * 待审核列表
     */
    public VueResult queryList() throws Exception {
        VueListResult result=getVueListResult("入库付款账单",PayAmount.class,actionUrl("queryList"));
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("付款单号", "orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("收款客户", "guest.name", 100, true));
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toDateColumn("付款时间", "payDate", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(getStatusColumn());
        fillOrderColumn(result);
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("付款单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("收款客户","guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款时间","payDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }

    /*
     * 订单付款台账列表
     */
    public VueResult orderPayQuery() throws Exception {
        VueListResult result=getVueListResult("订单付款台账",PayAmountRecord.class,actionUrl("orderPayQuery"));
        result.addCol(toIndexColumn());
        result.addCol(toNumberColumn("本次付款金额", "payAmount", 120, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toLinkColumn("付款单号", "pay.orderNo", 100, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","pay.oid")
        ));
        result.addCol(toTextColumn("客户名称", "pay.guest.name", 150, true));
        result.addCol(toDateColumn("付款时间", "pay.payDate", 100, true));
        result.addCol(toNumberColumn("付款金额", "pay.payAmount", 100, true).setCount(ListCount.NONE));
        result.addCol(getStatusColumn("pay.status"));
        result.addCol(toTextColumn("登记人", "pay.inputUser.realname", 100, true));
        result.addCol(toDateColumn("录入时间", "pay.inputDate", 100, true));
        result.addCol(toTextColumn("审核人", "pay.checkUser.realname", 100, true));
        result.addCol(toDateColumn("审核时间", "pay.checkDate", 100, true));
        result.addCol(toTextColumn("类型", "stock.type", 100, true).setDictType("m.store.model.StockInfo!type"));
        result.addCol(toLinkColumn("入库单号", "stock.orderNo", 100, true,
            new ListEvent(actionUrl(StockInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","stock.oid")
        ));
        result.addCol(toDateColumn("入库日期", "stock.stockDate", 100, true));
        result.addCol(toNumberColumn("入库金额", "stock.stockAmount", 100, true).setCount(ListCount.NONE));
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("付款单号","pay.orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("客户名称","pay.guest.name",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("付款时间","pay.payDate",SearchType.DATE_RANGE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("pay.store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }
    public List<PayAmountRecord> getStockList() {
        return stockList;
    }

    public void setStockList(List<PayAmountRecord> stockList) {
        this.stockList = stockList;
    }

    public PayAmount getModel() {
        return model;
    }

    public void setModel(PayAmount model) {
        this.model = model;
    }
}
